package com.hdmp.auth.shiro;

import com.google.common.base.Strings;
import com.hdmp.auth.entity.SysUserEntity;
import com.hdmp.auth.service.SysUserService;
import com.hdmp.auth.util.PasswordHelper;
import com.hdmp.tool.bean.ResultBean;
import com.hdmp.tool.util.JsonUtils;
import com.hdmp.wework.service.WeixinTokenService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.PathMatchingFilter;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

/**
 * Created by fanzhenxing on 08/01/2018.
 */

public class WechatFilter extends PathMatchingFilter {



    @Autowired
    SysUserService userService;
    @Autowired
    WeixinTokenService tokenService;

    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        System.out.println("2222222222222222222222222222222222");
        Subject currentUser = SecurityUtils.getSubject();
        Object principal = currentUser.getPrincipal();
        if (principal != null) {
            System.out.println("login user is:" +  principal);
            return true;
        }
        String appid = request.getParameter("appId");
        String code = request.getParameter("code");
        if (!Strings.isNullOrEmpty(appid) && !Strings.isNullOrEmpty(code)) {
            System.out.println("appid:" + appid + ",code:" + code + "have not login");
            //String openId = tokenService.getOpenId(appid, code);
            String openId = "1234567";
            System.out.println("get openid is:" + openId);
            if(openId != null && openId != "") {
                System.out.println("***********************************************");
                System.out.println(openId);
                System.out.println("***********************************************");
                //通过对照表查询用户
                SysUserEntity userinfoEntity = userService.queryByName(openId);
                if (userinfoEntity == null) {
                    userinfoEntity = new SysUserEntity();
                    userinfoEntity.setOrgDbid(99);
                    userinfoEntity.setUsername(openId);
                    userinfoEntity.setPassword("123");
                    userinfoEntity.setStatus(0);
                    userinfoEntity.setCreateBy(111);
                    userinfoEntity.setCreateTime(new Date());
                    userinfoEntity.setModifyBy(111);
                    userinfoEntity.setModifyTime(new Date());
                    PasswordHelper passwordHelper = new PasswordHelper();
                    passwordHelper.encrptPassword(userinfoEntity);
                    userService.saveOrUpdate(userinfoEntity);
                }
                String userName = userinfoEntity.getUsername();
                Subject subject = SecurityUtils.getSubject();
                UsernamePasswordToken token = new UsernamePasswordToken(userName, "123");
                try {
                    subject.login(token);
                    return true;
                } catch (AuthenticationException e) {
                    e.printStackTrace();
                    System.out.println(userName + ",longin failure exception:" + "\n" + e);
                }
            }
        }
        ResultBean resultBean = new ResultBean();
        resultBean.setCode(500);
        resultBean.setMsg("系统提示：请先登陆系统");
        printResponse(request, resultBean, response);
        return false;
    }

    private void printResponse(ServletRequest request, ResultBean<String> resultBean, ServletResponse response) {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.setContentType("application/json;charset=utf-8");
        httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
        httpResponse.setHeader("Access-Control-Allow-Origin", ((HttpServletRequest)request).getHeader("Origin"));
        String message = JsonUtils.toJson(resultBean);
        try {
            PrintWriter out = httpResponse.getWriter();
            out.println(message);
            out.flush();
            out.close();
            System.out.println();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
